package model

import (
	"errors"
	"fmt"
	"time"
	"tools-api/src/common/db/database"

	"xorm.io/xorm"
)

// BookAccounts 收支账户
type BookAccounts struct {
	Id         int64     `json:"id"`
	Uuid       string    `json:"-"`
	Key        string    `json:"key"`
	Name       string    `json:"name"`
	MonthStart int       `json:"month_start"`
	Def        int       `json:"def"`
	Sort       int       `json:"sort"`
	CreatedAt  time.Time `xorm:"created" json:"-"`
	ModifiedAt time.Time `xorm:"updated" json:"-"`
	DeleteMark int       `xorm:"delete_mark" json:"-"`
}

func (account BookAccounts) Create() int64 {
	_ = database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		var sort int // 自动计算排序值
		_, _ = session.Table(BookAccounts{}).Where("uuid = ?", account.Uuid).Select("(IFNULL(MAX(sort), 0) + 1) as sort").Get(&sort)
		account.Sort = sort
		_, _ = session.Insert(&account)
		return nil
	})
	return account.Id
}

// Delete 虚拟删除
func (BookAccounts) Delete(session *xorm.Session, uuid string, id int64) error {
	rows, err := session.Where("id=? and uuid=?", id, uuid).Cols("delete_mark").Update(&BookAccounts{DeleteMark: 1})
	if err != nil {
		return err
	}
	if rows == 0 {
		return errors.New("无权限")
	}
	return nil
}

// SetDefaultAccount 设置默认收支账户
func (BookAccounts) SetDefaultAccount(uuid string, id int64) error {
	sql := fmt.Sprintf("UPDATE book_accounts SET def = case id when %d then 1 else 0 end where uuid= '%s'", id, uuid)
	res, err := database.JCJEngine.Exec(sql)
	if err != nil {
		return err
	}
	affectedRows, _ := res.RowsAffected()
	if affectedRows == 0 {
		return errors.New("设置失败")
	}
	return nil
}

// GetDefaultAccount 获取默认收支账户
func (account BookAccounts) GetDefaultAccount(uuid string) BookAccounts {
	_, _ = database.JCJEngine.Where("uuid=? and delete_mark=0 and def=1", uuid).Get(&account)
	return account
}

// GetAccountById 根据id获取
func (account BookAccounts) GetAccountById(id int64) BookAccounts {
	_, _ = database.JCJEngine.Where("id=? and delete_mark=0", id).Get(&account)
	return account
}
